package cn.itsource.ymcc.config;

import cn.itsource.ymcc.constants.BaseConstants;
import cn.itsource.ymcc.handler.AuthorizeFailHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.util.AntPathMatcher;

//资源服务配置
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
//开启方法授权
public class BaseResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private AuthorizeFailHandler authorizeFailHandler;

    /**======================================================================================
     * 方法描述：1.资源服务安全配置
     ======================================================================================*/

    //1.1JWT令牌
    @Bean
    @Primary
    public TokenStore tokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    //1.2.JWT令牌校转换
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //设置JWT签名密钥。它可以是简单的MAC密钥，也可以是RSA密钥
        jwtAccessTokenConverter.setSigningKey(BaseConstants.Uaa.SIGN_KEY);
        return jwtAccessTokenConverter;
    }

    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());
    }

    //2.资源服务的资源的授权配置，比如那些资源放行，那些资源需要什么权限等等
    public void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().
                accessDeniedHandler(authorizeFailHandler)
                .authenticationEntryPoint(authorizeFailHandler);
    }

}